package edu.study.ops.controller;

import edu.study.api.common.dto.BaseRespDto;
import edu.study.api.common.dto.RespDto;
import edu.study.api.common.enums.BaseResultCodeEnum;
import edu.study.common.exception.BizException;
import edu.study.common.exception.ExceptionHandler;
import edu.study.common.util.file.FileTools;
import edu.study.common.util.log.Loggers;
import edu.study.common.validation.RequestValidator;
import edu.study.ops.dto.FileInfoDto;
import edu.study.ops.req.DownloadBatchFilesReq;
import edu.study.ops.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/api/ops/oss")
@Api(value = "/api/ops/oss", produces = "oss下载文件")
public class DownloadApiImpl {

    @Autowired
    private OssService ossService;
    
    @ApiOperation("下载文件")
    @RequestMapping(path = "/downLoad", method = RequestMethod.POST)
    public void downLoad(@RequestParam(name = "fileUrl", required = true) String fileUrl, HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        try {
            RespDto<byte[]> respDto = null;
            respDto = ossService.downFile(fileUrl);
            byte[] data = respDto.getData();
            outputStream = response.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            Loggers.api.info("文件下载异常，异常信息:{}", e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                Loggers.api.info("流关闭异常，异常信息:{}", e);
            }
        }
    }

    @ApiOperation("下载批量文件")
    @RequestMapping(path = "/downloadBatchFiles", method = RequestMethod.POST)
    public void downloadBatchFiles(@RequestBody DownloadBatchFilesReq req, HttpServletResponse response) {
        Loggers.api.info("downloadBatchFiles req={}", req);
        RequestValidator.validate(req);
        ZipOutputStream zipOutputStream = null;
        String fileName = "资产模板";
        try {
        	StringBuffer sbf = new StringBuffer("attachment;filename=").append(URLEncoder.encode(fileName,"UTF-8")).append(".zip");
            response.addHeader("Content-Disposition", sbf.toString());
            response.setContentType("application/x-zip-compressed");
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            for (FileInfoDto fileInfo : req.getFileInfoList()) {
                RespDto<byte[]> ossResp = ossService.downFile(fileInfo.getFileUrl());
                if (ossResp == null || !ossResp.isSuccess()) {
                	StringBuffer tempSbf = new StringBuffer("从OSS上下载文件").append(fileInfo.getFileUrl()).append("失败!");
                    throw new BizException(BaseResultCodeEnum.EXCEPTION.getCode(), tempSbf.toString());
                }
                FileTools.byteArrayToZipFile(zipOutputStream, fileInfo.getFileName(), ossResp.getData());
            }
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (Exception e) {
            ExceptionHandler.handleFailFast(new BaseRespDto(), e);
        } finally {
            try {
                if (zipOutputStream != null) {
                    zipOutputStream.close();
                }
            } catch (IOException io) {
            	Loggers.api.error("DownloadApiImpl.downloadBatchFiles fail to close ServletOutputStream.");
            }
        }
    }
}
